import type { VbenFormSchema } from '#/adapter/form'
import { treeToList } from '#/helper/treeHelper'
import { localesMenuOptions } from '#/utils/localesConfig'
import type { ExtendedFormApi } from '@vben/common-ui'
import { z } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { isEmpty } from '@vben/utils'
import { Button, Input, Popover } from 'ant-design-vue'
import type { Ref } from 'vue'
import { computed, ref } from 'vue'

const isMenu = (type: number) => type === 0
const isButton = (type: number) => type === 1
// 是否是内链
const isInnerLink = (target: '_blank' | '_self') => target === '_self'

const componentPathOptions = Object.keys(import.meta.glob('/src/views/**/*.vue')).map((v) => {
    const path = v.replace('/src/views', '')
    const name = path.replace('.vue', '')
    return {
        label: name,
        value: name
    }
})

const searchcomponentRouter = ref('')

const componentRouterOptionsOrgin = componentPathOptions.map((v) => {
    const name = v.value.replace(/\/index$/, '')
    return {
        label: name,
        value: name
    }
})

const componentRouterOptions = computed(() => {
    return componentRouterOptionsOrgin.filter((v) => {
        return v.value.includes(searchcomponentRouter.value)
    })
})

export function getAddEditFormSchema(opts?: {
    formApi?: ExtendedFormApi
    rowId: Ref<null | number>
    treeData: any[]
}) {
    const { formApi, treeData, rowId } = opts || {}
    const treeList = treeToList(treeData || [])

    const permissionOptions = [
        {
            label: $t('common.create'),
            value: 'add'
        },
        {
            label: $t('common.edit'),
            value: 'edit'
        },
        {
            label: $t('common.details'),
            value: 'view'
        },
        {
            label: $t('common.delete'),
            value: 'delete'
        },
        {
            label: $t('common.approval'),
            value: 'approval'
        },
        {
            label: $t('common.status'),
            value: 'status'
        },
        {
            label: $t('common.export'),
            value: 'export'
        },
        {
            label: $t('common.import'),
            value: 'import'
        },
        {
            label: $t('common.confirm'),
            value: 'confirm'
        },
        {
            label: $t('common.close'),
            value: 'close'
        },
        {
            label: $t('common.cancel'),
            value: 'cancel'
        },
        {
            label: $t('common.list'),
            value: 'index'
        }
    ]

    return [
        {
            fieldName: 'type',
            label: $t('page.system.children.menu.children.options.type.title'),
            component: 'RadioGroup',
            rules: 'required',
            defaultValue: 0,
            componentProps: {
                buttonStyle: 'solid',
                options: [
                    { label: $t('page.system.children.menu.children.options.type.menu'), value: 0 },
                    {
                        label: $t('page.system.children.menu.children.options.type.button'),
                        value: 1
                    }
                ]
            }
        },

        {
            fieldName: 'target',
            label: $t('page.system.children.menu.children.options.target.title'),
            component: 'RadioGroup',
            rules: 'required',
            defaultValue: '_self',
            componentProps: {
                options: [
                    {
                        label: $t('page.system.children.menu.children.options.target.self'),
                        value: '_self'
                    },
                    {
                        label: $t('page.system.children.menu.children.options.target.blank'),
                        value: '_blank'
                    }
                ]
            },
            dependencies: {
                triggerFields: ['type'],
                if(values) {
                    return isMenu(values.type)
                }
            }
        },
        {
            fieldName: 'pid',
            label: $t('page.system.children.menu.children.form.pid'),
            component: 'TreeSelect',
            rules: 'selectRequired',
            componentProps: {
                class: 'w-full',
                fieldNames: { children: 'children', label: 'title', value: 'id' },
                treeData,
                'tree-default-expand-all': true
            },
            dependencies: {
                triggerFields: ['pid'],
                rules(values) {
                    if (values.pid === rowId?.value) {
                        return z.number().refine(() => false, {
                            message: $t('page.system.children.menu.children.message.pidCannotSelf')
                        })
                    }
                }
            },
            renderComponentContent: () => ({
                title(form: any) {
                    return <div>{$t(form.title)}</div>
                }
            })
        },
        {
            fieldName: 'title',
            label: $t('page.system.children.menu.children.form.name'),
            component: 'TreeSelect',
            rules: 'selectRequired',
            componentProps: {
                'show-search': true,
                class: 'w-full',
                treeData: localesMenuOptions,
                // 'tree-default-expand-all': true,
                filterOption(input: string, option: any) {
                    return option.label.toLowerCase().includes(input.toLowerCase())
                }
            },
            dependencies: {
                triggerFields: ['type'],
                trigger(values) {
                    formApi?.updateSchema([
                        {
                            fieldName: 'title',
                            label: isMenu(values.type)
                                ? $t('page.system.children.menu.children.form.menuName')
                                : $t('page.system.children.menu.children.form.buttonName')
                        }
                    ])
                }
            }
        },

        {
            fieldName: 'icon',
            label: $t('page.system.children.menu.children.form.icon'),
            component: 'IconPicker',
            help: $t('page.system.children.menu.children.message.iconHelp'),
            componentProps: {
                placeholder: $t('page.system.children.menu.children.message.iconPlaceholder')
            },
            dependencies: {
                triggerFields: ['type'],
                if(values) {
                    return isMenu(values.type)
                }
            }
        },
        {
            fieldName: 'permission',
            label: $t('page.system.children.menu.children.form.permission'),
            component: 'Input',
            componentProps: {
                placeholder: $t('page.system.children.menu.children.message.permissionPlaceholder'),
                mode: 'tags'
            },
            defaultValue: '',
            dependencies: {
                triggerFields: ['type', 'permission'],
                required(values) {
                    return isButton(values.type)
                },
                rules(values) {
                    const value = values.permission

                    if (!isEmpty(value) && rowId) {
                        const item = treeList.find(
                            (v: any) => v.id !== rowId.value && v.permission === value
                        )

                        if (item) {
                            return z.string().refine(() => false, {
                                message: $t(
                                    'page.system.children.menu.children.message.permissionHasSelected',
                                    {
                                        title: item.title
                                    }
                                )
                            })
                        }
                    }
                }
            },
            renderComponentContent: (values) => ({
                suffix(form: any) {
                    const { formContext } = form
                    const permission = values.pid
                        ? treeList.find((v: any) => v.id === values.pid)?.permission
                        : ''

                    return (
                        <div>
                            {permission ? (
                                <Popover
                                    title={$t(
                                        'page.system.children.menu.children.message.permissionPopoverTitle'
                                    )}
                                    v-slots={{
                                        content() {
                                            return (
                                                <div style="height: 400px;width:300px; overflow: auto;">
                                                    {permissionOptions.map((v) => {
                                                        return (
                                                            <div
                                                                class="cursor-pointer pb-2 pt-2 hover:text-pink-600"
                                                                onClick={() => {
                                                                    formContext.setValue(
                                                                        `${permission}:${v.value}`
                                                                    )
                                                                }}
                                                                style="border-top: 1px solid #f0f0f0;"
                                                                title={$t('common.createTo')}
                                                            >
                                                                <p>{v.label}</p>
                                                                <p>
                                                                    {permission}:{v.value}
                                                                </p>
                                                            </div>
                                                        )
                                                    })}
                                                </div>
                                            )
                                        }
                                    }}
                                >
                                    <Button class="ml-2" size="small" type="link">
                                        {$t(
                                            'page.system.children.menu.children.action.addPermissionToParent'
                                        )}
                                    </Button>
                                </Popover>
                            ) : (
                                ''
                            )}
                        </div>
                    )
                }
            })
        },
        {
            fieldName: 'path',
            label: $t('page.system.children.menu.children.form.path'),
            component: 'Input',
            help: '',
            defaultValue: '',
            dependencies: {
                triggerFields: ['type', 'target'],
                if(values) {
                    return isMenu(values.type)
                },
                trigger(values) {
                    formApi?.updateSchema([
                        {
                            fieldName: 'path',
                            help: isInnerLink(values.target)
                                ? $t('page.system.children.menu.children.message.pathHelp')
                                : $t('page.system.children.menu.children.message.outsidePathHelp'),
                            label: isInnerLink(values.target)
                                ? $t('page.system.children.menu.children.form.path')
                                : $t('page.system.children.menu.children.form.outsidePath')
                        }
                    ])
                },
                rules(values) {
                    return z.string().min(1, {
                        message: $t('ui.formRules.required', [
                            isInnerLink(values.target)
                                ? $t('page.system.children.menu.children.form.path')
                                : $t('page.system.children.menu.children.form.outsidePath')
                        ])
                    })
                }
            },
            renderComponentContent: (values) => ({
                suffix(form: any) {
                    const { formContext } = form

                    return (
                        <div>
                            {isInnerLink(values.target) ? (
                                <Popover
                                    title={$t(
                                        'page.system.children.menu.children.action.quickSelection'
                                    )}
                                    v-slots={{
                                        content() {
                                            return (
                                                <div>
                                                    <Input
                                                        onUpdate:value={(val: string) => {
                                                            searchcomponentRouter.value = val
                                                        }}
                                                        value={searchcomponentRouter.value}
                                                    ></Input>
                                                    <div style="height: 400px;width:300px; overflow: auto;">
                                                        {componentRouterOptions.value.map((v) => {
                                                            return (
                                                                <div
                                                                    class="cursor-pointer pb-2 pt-2 hover:text-pink-600"
                                                                    onClick={() => {
                                                                        formContext.setValue(
                                                                            v.value
                                                                        )
                                                                        searchcomponentRouter.value =
                                                                            ''
                                                                    }}
                                                                    style="border-top: 1px solid #f0f0f0;"
                                                                    title={$t('common.createTo')}
                                                                >
                                                                    <p>{v.label}</p>
                                                                </div>
                                                            )
                                                        })}
                                                    </div>
                                                </div>
                                            )
                                        }
                                    }}
                                >
                                    <Button class="ml-2" size="small" type="link">
                                        {$t(
                                            'page.system.children.menu.children.action.quickSelection'
                                        )}
                                    </Button>
                                </Popover>
                            ) : (
                                ''
                            )}
                        </div>
                    )
                }
            })
        },
        {
            fieldName: 'component',
            label: $t('page.system.children.menu.children.form.component'),
            component: 'Select',
            defaultValue: '',
            componentProps: {
                class: 'w-full',
                options: componentPathOptions,
                showSearch: true
            },
            dependencies: {
                triggerFields: ['type', 'target'],
                if(values) {
                    return isMenu(values.type) && isInnerLink(values.target)
                }
            }
        },
        {
            fieldName: 'sort',
            label: $t('common.sort'),
            component: 'Input',
            defaultValue: '',
            rules: 'required',
            componentProps: {
                class: 'w-full',
                type: 'number'
            },
            renderComponentContent: (values) => ({
                suffix(form: any) {
                    const { formContext } = form
                    const sort = values.pid
                        ? treeList
                              .find((v: any) => v.id === values.pid)
                              ?.children?.sort(
                                  (a: any, b: any) => (b.sort || 0) - (a.sort || 0)
                              )?.[0]?.sort || ''
                        : ''

                    return (
                        <div>
                            {sort ? (
                                <Button
                                    class="ml-2"
                                    onClick={() => {
                                        if (typeof Number(sort) === 'number') {
                                            formContext.setValue(Number(sort) + 1)
                                        }
                                    }}
                                    size="small"
                                    type="link"
                                >
                                    {$t('page.system.children.menu.children.action.increment')}
                                </Button>
                            ) : (
                                ''
                            )}
                        </div>
                    )
                }
            })
        },
        {
            fieldName: 'status',
            label: $t('options.visible.title'),
            component: 'Switch',
            defaultValue: 1,
            rules: 'required',
            componentProps: {
                checkedValue: 1,
                unCheckedValue: 2,
                checkedChildren: $t('options.visible.children.visible'),
                unCheckedChildren: $t('options.visible.children.hidden')
            },
            dependencies: {
                triggerFields: ['type'],
                if(values) {
                    return isMenu(values.type)
                }
            }
        }
    ] as VbenFormSchema[]
}
